package net.yegong.util.reflect;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * The TypeTraits contains the basic type information which is missing in java core.
 * @author cooper
 * 
 */
public class TypeTraits {
	
	public static boolean isPrimitive(Class<?> clazz) {
		return PRIMITIVE_TO_WRAPPER.containsKey(clazz);
	}
	
	public static boolean isWrapper(Class<?> clazz) {
		return WRAPPER_TO_PRIMITIVE.containsKey(clazz);
	}
	
	public static Class<?> toPrimitive(Class<?> clazz) {
		Class<?> retVal = WRAPPER_TO_PRIMITIVE.get(clazz);
		retVal = null == retVal ? clazz : retVal;
		return retVal;
	}
	
	public static Class<?> toWrapper(Class<?> clazz) {
		Class<?> retVal = PRIMITIVE_TO_WRAPPER.get(clazz);
		retVal = null == retVal ? clazz : retVal;
		return retVal;
	}
	
	public static Class<?>[] toPrimitive(Class<?>[] clazz) {
		Class<?>[] retVal = new Class<?>[clazz.length];
		for (int i=0; i<clazz.length; ++i) {
			retVal[i] = toPrimitive(clazz[i]);
		}
		return retVal;
	}
	
	public static Class<?>[] toWrapper(Class<?> clazz[]) {
		Class<?>[] retVal = new Class<?>[clazz.length];
		for (int i=0; i<clazz.length; ++i) {
			retVal[i] = toWrapper(clazz[i]);
		}
		return retVal;
	}
	
	private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER;
	private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE;
	
	static {
		Map<Class<?>, Class<?>> p2w = new HashMap<Class<?>, Class<?>>();
		Map<Class<?>, Class<?>> w2p = new HashMap<Class<?>, Class<?>>();
		p2w.put(boolean.class, Boolean.class);
		p2w.put(char.class, Character.class);
		p2w.put(byte.class, Byte.class);
		p2w.put(short.class, Short.class);
		p2w.put(int.class, Integer.class);
		p2w.put(long.class, Long.class);
		p2w.put(float.class, Float.class);
		p2w.put(double.class, Double.class);
		p2w.put(void.class, Void.class);
		
		w2p.put(Boolean.class, boolean.class);
		w2p.put(Character.class, char.class);
		w2p.put(Byte.class, byte.class);
		w2p.put(Short.class, short.class);
		w2p.put(Integer.class, int.class);
		w2p.put(Long.class, long.class);
		w2p.put(Float.class, float.class);
		w2p.put(Double.class, double.class);
		w2p.put(Void.class, void.class);
		
		PRIMITIVE_TO_WRAPPER = Collections.unmodifiableMap(p2w);
		WRAPPER_TO_PRIMITIVE = Collections.unmodifiableMap(w2p);
	}
}
